export default {
  install(Vue, options) {
    const { wsUrl, store } = options;

    const websocketService = {
      ws: null,
      messageCallback: null,

      connect(username) {
        console.log("【WebSocket】开始连接...");
        console.log("【WebSocket】用户名:", username);
        if (!username) {
          console.warn("【WebSocket】用户名为空，无法连接");
          return;
        }

        const urlWithUser = wsUrl.replace(":username", encodeURIComponent(username));
        console.log("【WebSocket】连接的 URL:", urlWithUser);

        this.ws = new WebSocket(urlWithUser);

        this.ws.onopen = () => {
          console.log("【WebSocket】已成功连接到服务器 ✅");
        };

        this.ws.onmessage = (event) => {
          let receivedMsg;
          try {
            receivedMsg = JSON.parse(event.data);
            console.log("【WebSocket】收到消息 📥", receivedMsg); // 👈 所有收到的消息都会在这里打印
          } catch (e) {
            console.error("【WebSocket】JSON 解析失败 ❌", event.data);
            return;
          }

          if (this.messageCallback) {
            console.log("【WebSocket】调用消息回调处理消息 ⏳");
            this.messageCallback(receivedMsg);
          } else {
            console.warn("【WebSocket】未设置消息回调函数，消息未被处理 ⚠️");
          }
        };

        this.ws.onerror = (error) => {
          console.error("【WebSocket】发生错误 ❗", error);
        };

        this.ws.onclose = () => {
          console.log("【WebSocket】连接已关闭 🔒");
        };
      },

      disconnect() {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
          console.log("【WebSocket】正在主动断开连接 🔁");
          this.ws.close();
        } else {
          console.warn("【WebSocket】当前连接不可关闭（可能未连接）⚠️");
        }
      },

      sendMessage(message) {
        console.log("【WebSocket】准备发送消息 📤", message);

        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
          this.ws.send(JSON.stringify(message));
          console.log("【WebSocket】消息已成功发送 ✅");
        } else {
          console.warn("【WebSocket】未连接或连接未打开，消息未发送 ⚠️");
        }
      },

      isConnected() {
        const connected = this.ws && this.ws.readyState === WebSocket.OPEN;
        console.log("【WebSocket】当前是否连接?", connected ? "✅ 是" : "❌ 否");
        return connected;
      },

      onMessage(callback) {
        console.log("【WebSocket】设置消息回调函数 ✅");
        this.messageCallback = callback;
      }
    };

    Vue.prototype.$websocket = websocketService;
  }
};